/**
 * 
 */
package com.jeeplus.modules.webhook;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeeplus.modules.cfm.entity.Cfm;
import com.jeeplus.modules.cfm.service.CfmService;
import com.jeeplus.modules.gift.entity.Gift;
import com.jeeplus.modules.gift.service.GiftService;
import com.jeeplus.modules.hkqy.entity.Hkqy;
import com.jeeplus.modules.hkqy.service.HkqyService;
import com.jeeplus.modules.ktq.entity.Ktq;
import com.jeeplus.modules.ktq.service.KtqService;
import com.jeeplus.modules.llbt.entity.Llbt;
import com.jeeplus.modules.llbt.service.LlbtService;
import com.jeeplus.modules.prize.entity.Prize;
import com.jeeplus.modules.prize.service.PrizeService;
import com.jeeplus.modules.shopbusorder.entity.ShopbusOrder;
import com.jeeplus.modules.shopbusorder.service.ShopbusOrderService;
import com.jeeplus.modules.vip.entity.Vip;
import com.jeeplus.modules.vip.service.VipService;
import com.jeeplus.modules.xfq.entity.Xfq;
import com.jeeplus.modules.xfq.service.XfqService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.jeeplus.common.utils.XMLUtil;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.api.OrderNumPrefix;
import com.jeeplus.modules.api.utils.AlipayUtils;
import com.jeeplus.modules.couponorder.entity.CouponOrder;
import com.jeeplus.modules.couponorder.service.CouponOrderService;
import com.jeeplus.modules.grouporder.entity.GroupOrder;
import com.jeeplus.modules.grouporder.service.GroupOrderService;
import com.jeeplus.modules.productorder.entity.ProductOrder;
import com.jeeplus.modules.productorder.service.ProductOrderService;
import com.jeeplus.modules.proxyorder.entity.ProxyOrder;
import com.jeeplus.modules.proxyorder.service.ProxyOrderService;
import com.jeeplus.modules.proxyproduct.entity.ProxyProduct;
import com.jeeplus.modules.proxyproduct.service.ProxyProductService;
import com.jeeplus.modules.rechargeorder.service.RechargeOrderService;
import com.jeeplus.modules.shop.entity.Shop;
import com.jeeplus.modules.shop.service.ShopService;
import com.jeeplus.modules.store.entity.Store;
import com.jeeplus.modules.store.service.StoreService;
import com.jeeplus.modules.xhq.entity.Xhq;
import com.jeeplus.modules.xhq.service.XhqService;

/**
 * 支付回调
 * 
 * @author mall
 *
 */
@Controller
@RequestMapping(value = "/webhook")
public class Beecloudy extends BaseController {
	private static final String ali = "1";
	private static final String wx = "2";

	@Autowired
	private RechargeOrderService rechargeOrderService;
	@Autowired
	private ProductOrderService productOrderService;
	@Autowired
	private GroupOrderService groupOrderService;
	@Autowired
	private CouponOrderService couponOrderService;
	@Autowired
	private ShopbusOrderService shopbusorderService;
	@Autowired
	private ShopService shopService;
	@Autowired
	private StoreService storeService;
	@Autowired
	private ProxyOrderService proxyOrderService;
	@Autowired
	private ProxyProductService proxyProductService;
	@Autowired
	private LlbtService llbtService;
	@Autowired
	private XhqService xhqService;
	@Autowired
	private GiftService giftService;
	@Autowired
	private KtqService ktqService;
	@Autowired
	private PrizeService prizeService;
	@Autowired
	private XfqService xfqService;
	@Autowired
	private VipService vipService;
	@Autowired
	private CfmService cfmService;
	@Autowired
	private HkqyService hkqyService;

	/**
	 * 微信原生支付回调
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/wxPayNotify")
	@ResponseBody
	public String wxPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		InputStream inStream = request.getInputStream();
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		logger.debug("~~~~~~~~~~~~~~~~微信支付成功~~~~~~~~~~~~~~~~");
		outSteam.close();
		inStream.close();
		String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
		Map<String, String> map = XMLUtil.doXMLParse(result);
		if (map != null) {
			logger.info("微信回调信息：" + map.toString());
			/*
			 * for (Object keyValue : map.keySet()) {
			 * System.out.println("微信支付回调返回：" + keyValue + "=" +
			 * map.get(keyValue)); }
			 */
			// 获取返回参数
			String retcode = map.get("return_code");
			String rescode = map.get("result_code");
			// 判断签名及结果
			if ("SUCCESS".equals(retcode) && "SUCCESS".equals(rescode)) {
				// String attach = map.get("attach").toString();// 自定义参数
				String out_trade_no = map.get("out_trade_no");// 订单号
				String transactionId = map.get("transaction_id");// 交易单号
				logger.debug("订单号：" + out_trade_no + "; 流水号：" + transactionId);

				// 此处写回调业务逻辑
				String orderId = out_trade_no;
//				String orderId = out_trade_no.substring(0, out_trade_no.length() - 4);


				if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.chongzhi)) {// 充值订单
					// 暂不处理
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.totalId)) {// 云店商品大订单号
					ProductOrder o = new ProductOrder();
					o.setTotalId(orderId);
					List<ProductOrder> list = productOrderService.findList(o);
					if (!list.isEmpty()) {
						productOrderService.pay(list, out_trade_no, wx,map.get("trade_type"));
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.couponOrder)) {// 代金券订单
					CouponOrder couponOrder = couponOrderService.get(orderId);
					if (couponOrder != null) {
						couponOrder.setPayType(wx);
						couponOrder.setPayDate(new Date());
						couponOrder.setPayNo(out_trade_no);
						couponOrder.setState("1");
						couponOrder.setTrade_type(map.get("trade_type"));
						couponOrderService.pay(couponOrder);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.BusinessOrder)) {// 附近商圈订单
					ShopbusOrder shopbusorder =shopbusorderService.get(orderId);
					if (shopbusorder != null) {
						shopbusorder.setPayType(wx);
						shopbusorder.setPayDate(new Date());
						shopbusorder.setPayNo(out_trade_no);
						shopbusorder.setState("2");
						shopbusorder.setTrade_type(map.get("trade_type"));
						shopbusorderService.pay(shopbusorder);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.groupOrder)) {// 拼团订单
					GroupOrder groupOrder = groupOrderService.get(orderId);
					if (groupOrder != null) {
						groupOrder.setState("1");
						groupOrder.setPayType(wx);
						groupOrder.setPayDate(new Date());
						groupOrder.setPayNo(out_trade_no);
						groupOrder.setTrade_type(map.get("trade_type"));
						groupOrderService.pay(groupOrder);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.shopOrder)) {// 实体商家入驻订单
					Shop shop = shopService.get(orderId);
					if (shop != null) {
						shop.setAuditState("1");
						shop.setPayType(wx);
						shop.setOrderNo(out_trade_no);
						shop.setTrade_type(map.get("trade_type"));
						shopService.pay(shop);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.storeOrder)) {// 厂家入驻订单
					Store store = storeService.get(orderId);
					if (store != null) {
						store.setAuditState("1");
						store.setPayType(wx);
						store.setOrderNo(out_trade_no);
						store.setTrade_type(map.get("trade_type"));
						storeService.pay(store);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.proxyOrder)) {// 批发云店铺订单
					ProxyOrder proxyOrder = proxyOrderService.get(orderId);
					if (proxyOrder != null) {
						proxyOrder.setState("1");
						proxyOrder.setPayDate(new Date());
						proxyOrder.setPayType(wx);
						proxyOrder.setOrderNo(out_trade_no);
						proxyOrder.setTrade_type(map.get("trade_type"));
						proxyOrderService.pay(proxyOrder);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.proxyProductOrder)) {// 增选产品订单
					ProxyProduct proxyProduct = proxyProductService.get(orderId);
					if (proxyProduct != null) {
						if("0".equals(proxyProduct.getOrderState())) {
							proxyProduct.setOrderState("1");
							proxyProduct.setPayDate(new Date());
							proxyProduct.setPayNo(out_trade_no);
							proxyProduct.setPayType(wx);
							proxyProduct.setTrade_type(map.get("trade_type"));
							proxyProductService.pay(proxyProduct);
						}
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.llbt)) {// 增选产品订单
					Llbt llbt = llbtService.getOrderno(orderId);
					if (llbt != null) {
						llbt.setState("1");
						llbt.setPayDate(new Date());
						llbt.setFinishdate(new Date());
						llbtService.pay(llbt);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.xhq)) {// 选货权订单
					Xhq xhq = xhqService.get(orderId);
					if (xhq != null) {
						xhq.setState("1");
						xhq.setPayDate(new Date());
						xhq.setFinishdate(new Date());
						xhqService.pay(xhq);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.gift)) {// 赠品支付订单
					Gift gift = giftService.get(orderId);
					if (gift != null) {
						gift.setState("1");
						gift.setPayDate(new Date());
						gift.setPayType(wx);
						gift.setFinishdate(new Date());
						giftService.pay(gift);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.KTQ)) {// 开通权支付订单
					Ktq ktq = ktqService.get(orderId);
					if (ktq != null) {
						ktq.setState("1");
						ktq.setPayDate(new Date());
						ktq.setPayType(wx);
						ktq.setFinishdate(new Date());
						ktqService.pay(ktq);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.JP)) {// 奖品支付订单
					Prize prize = prizeService.get(orderId);
					if (prize != null) {
						prize.setState("1");
						prize.setPayDate(new Date());
						prize.setPayType(wx);
						prize.setFinishdate(new Date());
						prizeService.pay(prize);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.XFQ)) {// 消费券支付订单
					Xfq xfq = xfqService.get(orderId);
					if (xfq != null) {
						xfq.setState("1");
						xfq.setPayDate(new Date());
						xfq.setPayType(wx);
						xfq.setFinishdate(new Date());
						xfqService.pay(xfq);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.VIP)) {// VIP支付订单
					Vip vip = vipService.get(orderId);
					if (vip != null) {
						vip.setState("1");
						vip.setPayDate(new Date());
						vip.setPayType(wx);
						vip.setFinishdate(new Date());
						vipService.pay(vip);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.CFM)) {// VIP支付订单
					Cfm cfm = cfmService.get(orderId);
					if (cfm != null) {
						cfm.setState("1");
						cfm.setPayDate(new Date());
						cfm.setPayType(wx);
						cfm.setFinishdate(new Date());
						cfmService.pay(cfm);
					}
				}  else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.HKQY)) {// 惠康区域代理开通
					Hkqy hkqy = hkqyService.get(orderId);
					if (hkqy != null) {
						hkqy.setState("1");
						hkqy.setPayDate(new Date());
						hkqy.setPayType(wx);
						hkqy.setFinishdate(new Date());
						hkqyService.pay(hkqy);
					}
				}
				else {// 云店商品订单
					ProductOrder productOrder = productOrderService.get(orderId);
					if (productOrder != null) {
						productOrder.setState("1");
						productOrder.setPayNo(out_trade_no);
						productOrder.setPayType(wx);
						productOrder.setTrade_type(map.get("trade_type"));
						productOrder.setPayDate(new Date());
						productOrderService.pay(productOrder);
					}
				}
				logger.debug("修改订单状态成功");
				out.write(XMLUtil.setXML("SUCCESS", "")); // 告诉微信服务器，我收到信息了，不要在调用回调action了
			}
		}
		return null;
	}

	/**
	 * 支付宝原生支付回调
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/aliPayNotify")
	@ResponseBody
	public String aliPay(HttpServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject receiveMap = AlipayUtils.getReceiveMap(request);
		logger.info("支付宝回调信息：" + receiveMap.toString());
		if (receiveMap.getBooleanValue("signVerified")) {
			String tradeStatus = receiveMap.getString("trade_status");
			if ("TRADE_SUCCESS".equals(tradeStatus)) {
//				if ("TRADE_FINISHED".equals(tradeStatus) || "TRADE_SUCCESS".equals(tradeStatus)) {
//				显示您一年后接收的异步订单状态是TRADE_FINISHED，APP支付接口默认退款有效期是12个月，您的订单创建支付成功后过了12个月后交易状态变为TRADE_FINISHED，这时就会触发TRADE_FINISHED的异步

					// 获取订单编号
				String orderId = receiveMap.getString("out_trade_no");
				if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.chongzhi)) {// 充值订单
					// 暂不处理
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.totalId)) {// 云店商品大订单号
					ProductOrder o = new ProductOrder();
					o.setTotalId(orderId);
					List<ProductOrder> list = productOrderService.findList(o);
					if (!list.isEmpty()) {
						productOrderService.pay(list, orderId, ali,"");
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.couponOrder)) {// 代金券订单
					CouponOrder couponOrder = couponOrderService.get(orderId);
					if (couponOrder != null) {
						couponOrder.setPayType(ali);
						couponOrder.setPayDate(new Date());
						couponOrder.setPayNo(orderId);
						couponOrder.setState("1");
						couponOrderService.pay(couponOrder);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.BusinessOrder)) {// 附近商圈订单
					ShopbusOrder shopbusorder =shopbusorderService.get(orderId);
					if (shopbusorder != null) {
						shopbusorder.setPayType(ali);
						shopbusorder.setPayDate(new Date());
						shopbusorder.setPayNo(orderId);
						shopbusorder.setState("2");
						shopbusorderService.pay(shopbusorder);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.groupOrder)) {// 拼团订单
					GroupOrder groupOrder = groupOrderService.get(orderId);
					if (groupOrder != null) {
						groupOrder.setState("1");
						groupOrder.setPayType(ali);
						groupOrder.setPayDate(new Date());
						groupOrder.setPayNo(orderId);
						groupOrderService.pay(groupOrder);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.shopOrder)) {// 实体商家入驻订单
					Shop shop = shopService.get(orderId);
					if (shop != null) {
						shop.setAuditState("1");
						shop.setPayType(ali);
						shop.setOrderNo(orderId);
						shopService.pay(shop);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.storeOrder)) {// 厂家入驻订单
					Store store = storeService.get(orderId);
					if (store != null) {
						store.setAuditState("1");
						store.setPayType(ali);
						store.setOrderNo(orderId);
						storeService.pay(store);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.proxyOrder)) {// 批发云店铺订单
					ProxyOrder proxyOrder = proxyOrderService.get(orderId);
					if (proxyOrder != null) {
						proxyOrder.setState("1");
						proxyOrder.setPayDate(new Date());
						proxyOrder.setPayType(ali);
						proxyOrder.setOrderNo(orderId);
						proxyOrderService.pay(proxyOrder);
					}
				}else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.proxyProductOrder)) {// 增选产品订单
					ProxyProduct proxyProduct = proxyProductService.get(orderId);
					if (proxyProduct != null) {
						if("0".equals(proxyProduct.getOrderState())){
							proxyProduct.setOrderState("1");
							proxyProduct.setPayDate(new Date());
							proxyProduct.setPayNo(orderId);
							proxyProduct.setPayType(ali);
							proxyProductService.pay(proxyProduct);
						}
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.llbt)) {// 增选产品订单
					Llbt llbt = llbtService.getOrderno(orderId);
					if (llbt != null) {
						llbt.setState("1");
						llbt.setPayDate(new Date());
						llbt.setFinishdate(new Date());
						llbtService.pay(llbt);
					}
				}else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.xhq)) {// 选货权订单
					Xhq xhq = xhqService.get(orderId);
					if (xhq != null) {
						xhq.setState("1");
						xhq.setPayDate(new Date());
						xhq.setFinishdate(new Date());
						xhqService.pay(xhq);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.gift)) {// 赠品支付订单
					Gift gift = giftService.get(orderId);
					if (gift != null) {
						gift.setState("1");
						gift.setPayDate(new Date());
						gift.setPayType(ali);
						gift.setFinishdate(new Date());
						giftService.pay(gift);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.KTQ)) {// 开通权支付订单
					Ktq ktq = ktqService.get(orderId);
					if (ktq != null) {
						ktq.setState("1");
						ktq.setPayDate(new Date());
						ktq.setPayType(ali);
						ktq.setFinishdate(new Date());
						ktqService.pay(ktq);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.JP)) {// 奖品支付订单
					Prize prize = prizeService.get(orderId);
					if (prize != null) {
						prize.setState("1");
						prize.setPayDate(new Date());
						prize.setPayType(ali);
						prize.setFinishdate(new Date());
						prizeService.pay(prize);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.XFQ)) {// 消费券支付订单
					Xfq xfq = xfqService.get(orderId);
					if (xfq != null) {
						xfq.setState("1");
						xfq.setPayDate(new Date());
						xfq.setPayType(ali);
						xfq.setFinishdate(new Date());
						xfqService.pay(xfq);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.VIP)) {// VIP支付订单
					Vip vip = vipService.get(orderId);
					if (vip != null) {
						vip.setState("1");
						vip.setPayDate(new Date());
						vip.setPayType(ali);
						vip.setFinishdate(new Date());
						vipService.pay(vip);
					}
				} else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.CFM)) {// VIP支付订单
					Cfm o = cfmService.get(orderId);
					if (o != null) {
						o.setState("1");
						o.setPayDate(new Date());
						o.setPayType(ali);
						o.setFinishdate(new Date());
						cfmService.pay(o);
					}
				}   else if (StringUtils.startsWithIgnoreCase(orderId, OrderNumPrefix.HKQY)) {// 惠康区域代理开通
					Hkqy hkqy = hkqyService.get(orderId);
					if (hkqy != null) {
						hkqy.setState("1");
						hkqy.setPayDate(new Date());
						hkqy.setPayType(ali);
						hkqy.setFinishdate(new Date());
						hkqyService.pay(hkqy);
					}
				}
				else {// 云店商品订单
					ProductOrder productOrder = productOrderService.get(orderId);
					if (productOrder != null) {
						productOrder.setState("1");
						productOrder.setPayNo(orderId);
						productOrder.setPayType(ali);
						productOrder.setPayDate(new Date());
						productOrderService.pay(productOrder);
					}
				}
			}
			return "success";
		}
		return "fail";
	}
}
